
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>KTV 商品管理</title>
  <style>
    body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f4f4f4; }
    h1, h2 { color: #333; }
    .container { max-width: 800px; margin: auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
    form { margin-bottom: 20px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
    input, select, button { width: 100%; padding: 10px; margin: 5px 0; box-sizing: border-box; border-radius: 4px; border: 1px solid #ccc; }
    button { background-color: #28a745; color: white; border: none; cursor: pointer; }
    button.delete { background-color: #dc3545; }
    button.edit { background-color: #ffc107; }
    ul { list-style-type: none; padding: 0; }
    li { background: #fff; padding: 15px; border: 1px solid #ddd; margin-bottom: 10px; border-radius: 5px; display: flex; justify-content: space-between; align-items: center; }
    .product-info { flex-grow: 1; }
    .actions { display: flex; gap: 10px; }
  </style>
</head>
<body>

  <div class="container">
    <h1>KTV 商品管理后台</h1>

    <!-- 添加/编辑商品表单 -->
    <h2>添加新商品</h2>
    <form id="product-form">
      <input type="hidden" id="productId">
      <input type="text" id="name" placeholder="商品名称" required>
      <input type="text" id="description" placeholder="商品描述">
      <input type="number" id="price" placeholder="价格" step="0.01" required>
      <input type="text" id="image" placeholder="图片URL">
      <select id="category" required>
        <!-- Categories will be populated by JS -->
      </select>
      <button type="submit">保存商品</button>
    </form>

    <!-- 商品列表 -->
    <h2>商品列表</h2>
    <ul id="product-list"></ul>

    <hr style="margin: 40px 0;">

    <!-- 订单管理 -->
    <h2>订单管理 (每5秒自动刷新)</h2>
    <ul id="order-list"></ul>
  </div>

  <script>
    const apiUrl = '/api/products';
    const productForm = document.getElementById('product-form');
    const productList = document.getElementById('product-list');
    const categorySelect = document.getElementById('category');
    
    let categories = [];

    // 获取并展示所有商品
    async function getProducts() {
      const response = await fetch(apiUrl);
      const data = await response.json();
      categories = data.categories;
      const products = data.products;

      // 填充分类下拉框
      categorySelect.innerHTML = categories.map(c => `<option value="${c.id}">${c.name}</option>`).join('');

      // 渲染商品列表
      productList.innerHTML = '';
      products.forEach(product => {
        const li = document.createElement('li');
        li.innerHTML = `
          <div class="product-info">
            <strong>${product.name}</strong> - ¥${product.price.toFixed(2)} <br>
            <small>${product.description}</small>
          </div>
          <div class="actions">
            <button class="edit" onclick="editProduct('${product.id}')">编辑</button>
            <button class="delete" onclick="deleteProduct('${product.id}')">删除</button>
          </div>
        `;
        productList.appendChild(li);
      });
    }

    // 处理表单提交 (添加或更新)
    productForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      const id = document.getElementById('productId').value;
      const productData = {
        name: document.getElementById('name').value,
        description: document.getElementById('description').value,
        price: document.getElementById('price').value,
        image: document.getElementById('image').value,
        category: document.getElementById('category').value,
      };

      const method = id ? 'PUT' : 'POST';
      const url = id ? `${apiUrl}/${id}` : apiUrl;

      await fetch(url, {
        method: method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(productData),
      });

      productForm.reset();
      document.getElementById('productId').value = '';
      getProducts();
    });

    // 编辑商品
    async function editProduct(id) {
      // Find product from the already fetched list to avoid a new API call
      const response = await fetch(apiUrl);
      const data = await response.json();
      const product = data.products.find(p => p.id === id);

      if (product) {
        document.getElementById('productId').value = product.id;
        document.getElementById('name').value = product.name;
        document.getElementById('description').value = product.description;
        document.getElementById('price').value = product.price; // CORRECTED: No more division
        document.getElementById('image').value = product.image;
        document.getElementById('category').value = product.category;
        window.scrollTo(0, 0);
      }
    }

    // 删除商品
    async function deleteProduct(id) {
      if (confirm('确定要删除这个商品吗？')) {
        await fetch(`${apiUrl}/${id}`, { method: 'DELETE' });
        getProducts();
      }
    }

    // 初始加载
    getProducts();

    // --- 订单管理 ---
    const orderList = document.getElementById('order-list');
    const ordersApiUrl = '/api/orders';

    // Render action buttons based on status
    function getActionButtons(order) {
      let buttons = '';
      if (order.status === '备货中') {
        buttons += `<button class="edit" onclick="updateOrderStatus('${order.orderId}', '配送中')">接单配送</button>`;
      }
      if (order.status === '配送中') {
        buttons += `<button onclick="updateOrderStatus('${order.orderId}', '已完成')">送达</button>`;
      }
      if (order.status !== '已完成' && order.status !== '已取消') {
         buttons += `<button class="delete" onclick="updateOrderStatus('${order.orderId}', '已取消')">取消订单</button>`;
      }
      return buttons;
    }

    async function getOrders() {
      try {
        const response = await fetch(ordersApiUrl);
        const orders = await response.json();
        
        orderList.innerHTML = ''; // Clear previous list
        if (orders.length === 0) {
          orderList.innerHTML = '<li>暂无订单</li>';
          return;
        }

        orders.forEach(order => {
          const li = document.createElement('li');
          const itemsHtml = order.items.map(item => `<span>${item.name} x${item.quantity}</span>`).join(', ');
          li.innerHTML = `
            <div class="product-info">
              <strong>订单号: ${order.orderId} (<span style="color:${order.statusTheme === 'success' ? 'green' : 'orange'}">${order.status}</span>)</strong><br>
              <small>包厢: ${order.roomId} | 时间: ${new Date(order.timestamp).toLocaleString()}</small><br>
              <small>商品: ${itemsHtml}</small>
            </div>
            <div class="actions">
              <strong>¥${order.totalAmount.toFixed(2)}</strong>
              ${getActionButtons(order)}
            </div>
          `;
          orderList.appendChild(li);
        });
      } catch (error) {
        console.error('Failed to fetch orders:', error);
        orderList.innerHTML = '<li>加载订单失败</li>';
      }
    }

    async function updateOrderStatus(orderId, newStatus) {
      await fetch(`${ordersApiUrl}/${orderId}/status`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus }),
      });
      getOrders(); // Refresh the list after updating
    }

    // 初始加载订单并设置定时刷新
    getProducts(); // Also load products on init
    getOrders();
    setInterval(getOrders, 5000); // Refresh every 5 seconds
  </script>

</body>
</html>
